package com.ycode.bang.anbang.utils;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.net.ParseException;
import android.net.Uri;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.WindowManager;
import android.widget.TextView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonTools {
	private static Context context;
	// 默认圆角半径
	private static final int DEFAULT_CORNER_RADIUS_DIP = 15;
	// 中间数字的颜色
	private static final int DEFAULT_NUM_COLOR = Color.parseColor("#CCFF0000");

	// 拨打电话
	public void call(final String phone, Context context) {
		this.context = context;
		new AlertDialog.Builder(context).setTitle("准备拨打电话")
				.setIcon(android.R.drawable.ic_dialog_info).setMessage(phone)
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				})
				.setPositiveButton("确认", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						Intent intent = new Intent(Intent.ACTION_CALL, Uri
								.parse("tel:" + phone));
						CommonTools.context.startActivity(intent);
					}
				}).show();
	}

	public void sendMessage(String phone, String content, Context context) {
		Uri uri;
		if (!TextUtils.isEmpty(phone)) {
			uri = Uri.parse("smsto:" + phone);
		} else {
			uri = Uri.parse("smsto:");
		}
		Intent it = new Intent(Intent.ACTION_SENDTO, uri);
		if (!TextUtils.isEmpty(content)) {
			it.putExtra("sms_body", content);
		}
		context.startActivity(it);
	}

	public void sendEmail(String email, String content, Context context) {
		Intent it = new Intent(Intent.ACTION_SENDTO);
		it.setData(Uri.parse("mailto:" + email));
		it.putExtra(Intent.EXTRA_TEXT, content);
		context.startActivity(it);

	}

	// 判断电话号码输入是否正确
	public static boolean isMobileNum(String mobiles) {
		Pattern p = Pattern
				.compile("^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

	public static boolean isNumAndLetter(String username) {
		Pattern p = Pattern.compile("^[0-9a-zA-Z]{1,20}$");
		Matcher m = p.matcher(username);
		return m.matches();
	}

	// "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$
	// "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$"
	// 判断邮箱号码输入是否正确
	public static boolean isEmail(String email) {
		Pattern p = Pattern
				.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
		Matcher m = p.matcher(email);
		return m.matches();
	}

	/**
	 * 判断是否为合法的日期时间字符串
	 * 
	 * @param str_input
	 * @param str_input
	 * @return boolean;符合为true,不符合为false
	 */
	public static boolean isDate(String str_input, String rDateFormat) {
		if (!isNull(str_input)) {
			SimpleDateFormat formatter = new SimpleDateFormat(rDateFormat);
			formatter.setLenient(false);
			try {
				formatter.format(formatter.parse(str_input));
			} catch (Exception e) {
				return false;
			}
			return true;
		}
		return false;
	}

	public static boolean isNull(String str) {
		if (str == null)
			return true;
		else
			return false;
	}

	/**
	 * 计算两个日期型的时间相差多少时间
	 * 
	 * @param startDate
	 *            开始日期
	 * @param endDate
	 *            结束日期
	 * @return
	 */
	public String twoDateDistance(Date startDate, Date endDate) {

		Date nowDate = Calendar.getInstance().getTime();

		if (startDate == null || endDate == null) {
			return null;
		}
		long timeLong = endDate.getTime() - startDate.getTime();
		if (timeLong < 60 * 1000)
			return timeLong / 1000 + "秒前";
		else if (timeLong < 60 * 60 * 1000) {
			timeLong = timeLong / 1000 / 60;
			return timeLong + "分钟前";
		} else if (timeLong < 60 * 60 * 24 * 1000) {
			timeLong = timeLong / 60 / 60 / 1000;
			return timeLong + "小时前";
		} else if (timeLong < 60 * 60 * 24 * 1000 * 7) {
			timeLong = timeLong / 1000 / 60 / 60 / 24;
			return timeLong + "天前";
		} else if (timeLong < 60 * 60 * 24 * 1000 * 7 * 4) {
			timeLong = timeLong / 1000 / 60 / 60 / 24 / 7;
			return timeLong + "周前";
		} else {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			sdf.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
			return sdf.format(startDate);
		}
	}

	/**
	 * 
	 * 
	 * @param startDate
	 *            开始日期
	 * @param nowDate
	 *            当前时间
	 * @return
	 */
	public static String OneDateDistance(String timeString) {

		// Date startDate = new Date(publishtime);//
		// publishtime为"E MMMM dd hh:mm:ss z yyyy"这种格式，

		Date startDate = getTime(timeString);
		Date nowDate = Calendar.getInstance().getTime();

		if (startDate == null || nowDate == null) {
			return null;
		}
		long timeLong = nowDate.getTime() - startDate.getTime();
		// System.out.println("----" + timeString + "---" + startDate.getTime()
		// + "---" + timeLong);
		int dayLong = nowDate.getDate() - startDate.getDate();
		// if (timeLong < 10 * 60 * 1000) {
		// return "10分钟内";
		// } else if (timeLong < 60 * 24 * 1000) {
		// return "1小时前内";
		// } else
		if (dayLong == 0) {
			return "今天" + timeString.substring(11, 16);
		} else if (dayLong == 1) {
			return "昨天" + timeString.substring(11, 16);
		} else {
			SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
			sdf.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
			return sdf.format(startDate);
		}
	}

	/*
	 * 判断时间是否为今天
	 */
	public static boolean judgeData(String str) {

		Date nowDate = Calendar.getInstance().getTime();
		SimpleDateFormat sdf;
		sdf = new SimpleDateFormat("yyyy-MM-dd");
		sdf.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
		if (str.equals(sdf.format(nowDate))) {
			return true;
		} else {
			return false;
		}
	}

	/*
	 * 时间转换 flag 为 0 转换为"HH:mm" 为1转换为MM-dd
	 */
	// public static String dataChange(String timeString, int flag) {
	// Date startDate = getTime(timeString);
	// SimpleDateFormat sdf;
	// if (flag == 0) {
	// sdf = new SimpleDateFormat("HH:mm");
	// } else {
	// sdf = new SimpleDateFormat("MM-dd");
	// }
	// sdf.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
	// return sdf.format(startDate);
	//
	// }

	// 得到当前星期的所有日期
	public static String[] getWeekToDay() {
		long longtime = System.currentTimeMillis();
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(longtime);
		int mYear = c.get(Calendar.YEAR);
		int mMonth = c.get(Calendar.MONTH) + 1;
		int mDay = c.get(Calendar.DAY_OF_MONTH);

		String[] str = new String[15];
		int w = c.get(Calendar.DAY_OF_WEEK) - 1;
		c.add(Calendar.DAY_OF_MONTH, -w);
		str[7] = w + ""; // 存当前为一个星期的第几天
		for (int i = 0; i < 7; i++) {
			mYear = c.get(Calendar.YEAR);
			mMonth = c.get(Calendar.MONTH) + 1;
			mDay = c.get(Calendar.DAY_OF_MONTH);
			str[i] = mMonth + "月" + mDay + "日";
			str[i + 8] = mYear + "-" + mMonth + "-" + mDay;
			c.add(Calendar.DAY_OF_MONTH, 1);
		}

		return str;

	}

	/*
	 * 得到当前为今年的第几周
	 */
	public static String[] getWeekNum() {
		long longtime = System.currentTimeMillis();
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(longtime);
		int mYear = c.get(Calendar.YEAR);
		int mMonth = c.get(Calendar.MONTH) + 1;
		int mDay = c.get(Calendar.DAY_OF_MONTH);

		int w = c.get(Calendar.WEEK_OF_YEAR);
		String[] str = { mYear + "", w + "" };

		return str;
	}

	/**
	 * 得到某年某周的第一天
	 * 
	 * @param year
	 * @param week
	 * @return
	 */
	public static String getFirstDayOfWeek(int year, int week) {
		Calendar c = Calendar.getInstance();
		c.set(Calendar.YEAR, year);
		c.set(Calendar.WEEK_OF_YEAR, week);
		c.get(Calendar.WEEK_OF_YEAR); // 此处不知为何要加上,不加显示的都是当前星期的第一天
		c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
		c.setFirstDayOfWeek(Calendar.SUNDAY);
		SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
		String firstDayOfWeek = sdf.format(c.getTime());
		return firstDayOfWeek;
	}

	/**
	 * 得到某年某周的最后一天
	 * 
	 * @param year
	 * @param week
	 * @return
	 */
	public static String getLastDayOfWeek(int year, int week) {
		Calendar c = Calendar.getInstance();
		c.set(Calendar.YEAR, year);
		c.set(Calendar.WEEK_OF_YEAR, week);
		c.get(Calendar.WEEK_OF_YEAR);
		c.setFirstDayOfWeek(Calendar.SUNDAY);
		c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6);
		SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
		String firstDayOfWeek = sdf.format(c.getTime());
		return firstDayOfWeek;
	}

	/**
	 * 得到某一年周的总数
	 * 
	 * @param year
	 * @return
	 */
	public static int getMaxWeekNumOfYear(int year) {
		Calendar c = Calendar.getInstance();
		c.set(Calendar.YEAR, 2015);
		c.set(Calendar.MONTH, 11);
		c.set(Calendar.DATE, 31);
		while (1 == c.get(Calendar.WEEK_OF_YEAR)) {
			c.set(Calendar.DATE, c.get(Calendar.DATE) - 1);
		}
		return c.get(Calendar.WEEK_OF_YEAR);
	}

	// 将字符串转为时间戳
	public static Date getTime(String user_time) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date d = null;
		try {
			d = sdf.parse(user_time);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (java.text.ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return d;
	}

	// 将图片转为字节流
	public static byte[] getBytesFromFile(File file) {
		byte[] ret = null;
		try {
			if (file == null) {
				// log.error("helper:the file is null!");
				return null;
			}
			FileInputStream in = new FileInputStream(file);
			ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
			byte[] b = new byte[4096];
			int n;
			while ((n = in.read(b)) != -1) {
				out.write(b, 0, n);
			}
			in.close();
			out.close();
			ret = out.toByteArray();
		} catch (IOException e) {
			// log.error("helper:get bytes from file process error!");
			e.printStackTrace();
		}
		return ret;
	}

	public static byte[] bitmapToBytes(Bitmap bitmap) {
		if (bitmap == null) {
			return null;
		}
		final ByteArrayOutputStream os = new ByteArrayOutputStream();
		// 将Bitmap压缩成PNG编码，质量为100%存储
		bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);// 除了PNG还有很多常见格式，如jpeg等。
		return os.toByteArray();
	}

	public static Bitmap preScaleBitmap(Bitmap temp, float drawScale,
			Context context) {
		// 得到手机屏幕宽度
		WindowManager wm = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		float screenWidth = wm.getDefaultDisplay().getWidth();
		// float scaleHeight=(int)((OularDataManager.deviceWidth-20)*drawScale);
		float scale = screenWidth / temp.getWidth();
		Matrix matrix = new Matrix();
		matrix.postScale(scale, scale);
		// matrix.postScale(0.5f, 0.5f);
		Bitmap temp2 = Bitmap.createBitmap(temp, 0, 0, temp.getWidth(),
				temp.getHeight(), matrix, true);
		return temp2;
	}

	/***
	 * 
	 * 生成有数字的图片(没有边框)
	 * 
	 * @param context
	 * @param icon
	 *            图片
	 * @param isShowNum
	 *            是否要绘制数字
	 * @param num
	 *            数字字符串：整型数字 超过99，显示为"99+"
	 * @return
	 */
	public static Bitmap generatorNumIcon(Context context, Bitmap icon,
			boolean isShowNum, String num) {

		DisplayMetrics dm = context.getResources().getDisplayMetrics();
		// 基准屏幕密度
		float baseDensity = 1.5f;// 240dpi
		float factor = dm.density / baseDensity;

		// 初始化画布
		int iconSize = (int) context.getResources().getDimension(
				android.R.dimen.app_icon_size);
		Bitmap numIcon = Bitmap.createBitmap(iconSize, iconSize,
				Config.ARGB_8888);
		Canvas canvas = new Canvas(numIcon);

		// 拷贝图片
		Paint iconPaint = new Paint();
		iconPaint.setDither(true);// 防抖动
		iconPaint.setFilterBitmap(true);// 用来对Bitmap进行滤波处理，这样，当你选择Drawable时，会有抗锯齿的效果
		Rect src = new Rect(0, 0, icon.getWidth(), icon.getHeight());
		Rect dst = new Rect(0, 0, iconSize, iconSize);
		canvas.drawBitmap(icon, src, dst, iconPaint);

		if (isShowNum) {

			if (TextUtils.isEmpty(num)) {
				num = "0";
			}

			if (!TextUtils.isDigitsOnly(num)) {
				// 非数字
				num = "0";
			}

			int numInt = Integer.valueOf(num);

			if (numInt > 99) {// 超过99
				num = "99+";
			}

			// 启用抗锯齿和使用设备的文本字体大小
			// 测量文本占用的宽度
			Paint numPaint = new Paint(Paint.ANTI_ALIAS_FLAG
					| Paint.DEV_KERN_TEXT_FLAG);
			numPaint.setColor(Color.WHITE);
			numPaint.setTextSize(25f * factor);
			numPaint.setTypeface(Typeface.DEFAULT_BOLD);
			int textWidth = (int) numPaint.measureText(num, 0, num.length());

			/**
			 * ----------------------------------* TODO 绘制圆角矩形背景 start
			 * ------------------------------------
			 */
			// 圆角矩形背景的宽度
			int backgroundHeight = (int) (2 * 15 * factor);
			int backgroundWidth = textWidth > backgroundHeight ? (int) (textWidth + 10 * factor)
					: backgroundHeight;

			canvas.save();// 保存状态

			ShapeDrawable drawable = getDefaultBackground(context);
			drawable.setIntrinsicHeight(backgroundHeight);
			drawable.setIntrinsicWidth(backgroundWidth);
			drawable.setBounds(0, 0, backgroundWidth, backgroundHeight);
			canvas.translate(iconSize - backgroundWidth, 0);
			drawable.draw(canvas);

			canvas.restore();// 重置为之前保存的状态

			/**
			 * ----------------------------------* TODO 绘制圆角矩形背景 end
			 * ------------------------------------
			 */

			// 绘制数字
			canvas.drawText(num,
					(float) (iconSize - (backgroundWidth + textWidth) / 2),
					22 * factor, numPaint);
		}
		return numIcon;
	}

	/***
	 * 得到一个默认的背景：圆角矩形<br>
	 * <br>
	 * 使用代码来生成一个背景：相当于用<shape>的xml的背景
	 * 
	 * @return
	 */
	private static ShapeDrawable getDefaultBackground(Context context) {

		// 这个是为了应对不同分辨率的手机，屏幕兼容性
		int r = dipToPixels(context, DEFAULT_CORNER_RADIUS_DIP);
		float[] outerR = new float[] { r, r, r, r, r, r, r, r };

		// 圆角矩形
		RoundRectShape rr = new RoundRectShape(outerR, null, null);
		ShapeDrawable drawable = new ShapeDrawable(rr);
		drawable.getPaint().setColor(DEFAULT_NUM_COLOR);// 设置颜色
		return drawable;

	}

	/***
	 * dp to px
	 * 
	 * @param dip
	 * @return
	 */
	public static int dipToPixels(Context context, int dip) {
		Resources r = context.getResources();
		float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip,
				r.getDisplayMetrics());
		return (int) px;
	}

	public static byte[] compressImage(Bitmap image) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 400 / (baos.toByteArray().length / 1024) * 100;

		// while (baos.toByteArray().length / 1024 > size) { //
		// 循环判断如果压缩后图片是否大于100kb,大于继续压缩
		// baos.reset();// 重置baos即清空baos
		// image.compress(Bitmap.CompressFormat.JPEG, options, baos);//
		// 这里压缩options%，把压缩后的数据存放到baos中
		// options -= 10;// 每次都减少10
		// }
		image.compress(Bitmap.CompressFormat.JPEG, options, baos);
		byte[] isBm = baos.toByteArray();// 把压缩后的数据baos存放到ByteArrayInputStream中
		return isBm;
	}

	public static int judgePWDStrength(String str) {
		int modes = 0;
		if (str.length() < 6&&str.length()>0) {
			return 1;
		}

		if (Pattern.compile(".*[0-9]+.*").matcher(str).matches())
			modes++; // 数字
		if (Pattern.compile(".*[a-z]+.*").matcher(str).matches())
			modes++; // 小写
		if (Pattern.compile(".*[A-Z]+.*").matcher(str).matches())
			modes++; // 大写
		if(Pattern.compile(".*[^A-Za-z0-9]+.*").matcher(str).matches())
			modes++; //特殊字符
		return modes;

	}

	/**
	 *
	 * @param context
	 * @param drawableRes －1为空
	 * @param textView
	 * @param leftOrRight 1为左，其它为右
	 */
	public static void setTextviewDrawable(Context context,int drawableRes,TextView textView,int
			leftOrRight){
		if(drawableRes == -1){
			textView.setCompoundDrawables(null, null, null, null);
		}else {
			Drawable drawable = context.getResources().getDrawable(drawableRes);
			/// 这一步必须要做,否则不会显示.
			drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
			if (leftOrRight == 1) {
				textView.setCompoundDrawables(drawable, null, null, null);
			} else {
				textView.setCompoundDrawables(null, null, drawable, null);
			}
		}
	}
}
